package com.zrt.pad.datasource.db;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.zrt.pad.commonui.SharedApplication;

public class CustomDBHelper extends SQLiteOpenHelper {

	private static final int version = 2;
	public static final String name = "zrtmenu.db";

	public CustomDBHelper(Context context) {
		super(context, name, null, version);
	}

	public CustomDBHelper(){
		super(SharedApplication.context, name, null, version);
	}
	
	public static final CustomDBHelper instance = new CustomDBHelper();

	private void execSqlWithDatabase(SQLiteDatabase db) {
		ArrayList<String> sqlList = new ArrayList<String>();
		//get sql
		try {
			InputStream is = getClass().getResource("/com/zrt/pad/datasource/db/init.sql").openStream();
			InputStreamReader isr = new InputStreamReader(is, "utf-8");
			BufferedReader br = new BufferedReader(isr);
			StringBuffer buffer = new StringBuffer(512);
			String line = br.readLine();
			while (line != null) {
				line = line.trim();
				if (line.endsWith(";")) {
					if (line.length() > 0) {
						buffer.append(line.substring(0, line.length() - 1));
					}
					sqlList.add(buffer.toString());
					buffer.delete(0, buffer.length());
				} else {
					buffer.append(line);
					buffer.append('\n');
				}
				//read next line
				line = br.readLine();
			}
			br.close();
			isr.close();
			is.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		//exec sql
		db.beginTransaction();
		for (String sql : sqlList) {
			db.execSQL(sql);
		}
		db.setTransactionSuccessful();
		db.endTransaction();
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		execSqlWithDatabase(db);
	}


	@Override
	public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {

	}

}
